import React, { useState, useEffect } from 'react';
import {Card, Table, Tag, Button, Modal, Form, Input, Select, Tree, message, Divider, Popconfirm, Row, Col, Typography} from 'antd';
import {PlusOutlined, EditOutlined, DeleteOutlined, LockOutlined, UserOutlined, DollarOutlined, AuditOutlined, SafetyOutlined} from '@ant-design/icons';
const { Title, Text } = Typography;
// const { Option } = Select;

// 模拟应用列表数据
const allApps = [
    { id: 'dashboard', name: '控制面板', icon: <UserOutlined /> },
    { id: 'user_management', name: '用户管理', icon: <UserOutlined /> },
    { id: 'financial', name: '财务系统', icon: <DollarOutlined /> },
    { id: 'audit', name: '审核系统', icon: <AuditOutlined /> },
    { id: 'report', name: '报表中心', icon: <SafetyOutlined /> },
    { id: 'settings', name: '系统设置', icon: <LockOutlined /> },
];

// 模拟初始角色数据
const initialRoles = [
    {
        id: 'admin',
        name: '管理员',
        description: '拥有所有权限',
        permissions: ['dashboard', 'user_management', 'financial', 'audit', 'report', 'settings']
    },
    {
        id: 'user',
        name: '普通用户',
        description: '基础权限',
        permissions: ['dashboard']
    },
    {
        id: 'finance',
        name: '财务人员',
        description: '财务相关权限',
        permissions: ['dashboard', 'financial', 'report']
    },
    {
        id: 'auditor',
        name: '审核人员',
        description: '审核相关权限',
        permissions: ['dashboard', 'audit']
    }
];

const RoleManagement = () => {
    const [roles, setRoles] = useState(initialRoles);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [currentRole, setCurrentRole] = useState(null);
    const [form] = Form.useForm();
    const [treeData, setTreeData] = useState([]);
    const [checkedKeys, setCheckedKeys] = useState([]);

    // 准备树形数据
    useEffect(() => {
        const formattedTreeData = allApps.map(app => ({
            title: (
                <span>
          {app.icon} {app.name}
        </span>
            ),
            key: app.id
        }));
        setTreeData(formattedTreeData);
    }, []);

    // 显示添加角色对话框
    const showAddModal = () => {
        setCurrentRole(null);
        form.resetFields();
        setCheckedKeys([]);
        setIsModalVisible(true);
    };

    // 显示编辑角色对话框
    const showEditModal = (role) => {
        setCurrentRole(role);
        form.setFieldsValue({
            name: role.name,
            description: role.description
        });
        setCheckedKeys(role.permissions);
        setIsModalVisible(true);
    };

    // 处理表单提交
    const handleSubmit = () => {
        form.validateFields().then(values => {
            const { name, description } = values;
            const permissions = checkedKeys;

            if (currentRole) {
                // 更新角色
                setRoles(roles.map(role =>
                    role.id === currentRole.id ? { ...role, name, description, permissions } : role
                ));
                message.success('角色更新成功');
            } else {
                // 添加新角色
                const newRole = {
                    id: `role_${Date.now()}`,
                    name,
                    description,
                    permissions
                };
                setRoles([...roles, newRole]);
                message.success('角色添加成功');
            }

            setIsModalVisible(false);
        });
    };

    // 删除角色
    const handleDelete = (roleId) => {
        setRoles(roles.filter(role => role.id !== roleId));
        message.success('角色删除成功');
    };

    // 树形选择框变化
    const onCheck = (checkedKeys) => {
        setCheckedKeys(checkedKeys);
    };

    // 表格列定义
    const columns = [
        {
            title: '角色名称',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => (
                <div>
                    {getRoleIcon(record.name)}
                    <span style={{ marginLeft: 8 }}>{text}</span>
                </div>
            )
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description'
        },
        {
            title: '权限',
            dataIndex: 'permissions',
            key: 'permissions',
            render: (permissions) => (
                <div>
                    {permissions.map(permissionId => {
                        const app = allApps.find(a => a.id === permissionId);
                        return app ? (
                            <Tag key={permissionId} icon={app.icon} color="blue" style={{ marginBottom: 4 }}>
                                {app.name}
                            </Tag>
                        ) : null;
                    })}
                </div>
            )
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_, record) => (
                <span>
          <Button
              type="link"
              icon={<EditOutlined />}
              onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Divider type="vertical" />
          <Popconfirm
              title="确定要删除这个角色吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>删除</Button>
          </Popconfirm>
        </span>
            )
        }
    ];

    // 根据角色名称获取图标
    const getRoleIcon = (roleName) => {
        switch (roleName) {
            case '管理员':
                return <SafetyOutlined style={{ color: '#f5222d' }} />;
            case '普通用户':
                return <UserOutlined style={{ color: '#1890ff' }} />;
            case '财务人员':
                return <DollarOutlined style={{ color: '#52c41a' }} />;
            case '审核人员':
                return <AuditOutlined style={{ color: '#faad14' }} />;
            default:
                return <UserOutlined />;
        }
    };

    return (
        <div style={{ padding: 24 }}>
            <Card variant={false}>
                <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
                    <Col>
                        <Title level={4} style={{ margin: 0 }}>
                            <SafetyOutlined style={{ marginRight: 12 }} />
                            角色权限管理
                        </Title>
                        <Text type="secondary">管理系统各角色的访问权限</Text>
                    </Col>
                    <Col>
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={showAddModal}
                        >
                            新增角色
                        </Button>
                    </Col>
                </Row>

                <Table
                    columns={columns}
                    dataSource={roles}
                    rowKey="id"
                    bordered
                    pagination={{ pageSize: 5 }}
                />
            </Card>

            {/* 添加/编辑角色对话框 */}
            <Modal
                title={currentRole ? '编辑角色' : '新增角色'}
                open={isModalVisible}
                onOk={handleSubmit}
                onCancel={() => setIsModalVisible(false)}
                width={700}
                destroyOnHidden={ true}
            >
                <Form form={form} layout="vertical">
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="name"
                                label="角色名称"
                                rules={[{ required: true, message: '请输入角色名称' }]}
                            >
                                <Input placeholder="例如：管理员、财务人员等" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="description"
                                label="角色描述"
                                rules={[{ required: true, message: '请输入角色描述' }]}
                            >
                                <Input placeholder="简要描述角色的职责" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Form.Item label="权限分配">
                        <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                            选择该角色可以访问的应用系统
                        </Text>
                        <Tree
                            checkable
                            treeData={treeData}
                            checkedKeys={checkedKeys}
                            onCheck={onCheck}
                            selectable={false}
                            height={200}
                            style={{
                                border: '1px solid #d9d9d9',
                                borderRadius: 4,
                                padding: '8px 12px'
                            }}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default RoleManagement;